package com.whfc.ms.queue;

import com.whfc.common.constant.QueueConst;
import com.whfc.common.util.JSONUtil;
import com.whfc.fuum.dto.SysUserDTO;
import com.whfc.fuum.service.SysUserService;
import com.whfc.mach.dto.obd.MaintainWebsocketDTO;
import com.whfc.ms.websocket.WebSocketSessionManager;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/12/2 11:59
 */
@Component
@RabbitListener(queues = QueueConst.OBD_MAINTAIN_DATA)
public class MaintainQueueMessageListener {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WebSocketSessionManager sessionManager;

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0")
    private SysUserService sysUserService;

    @RabbitHandler
    public void process(String textMsg) {
        logger.info("maintain_listener,{}", textMsg);
        try {
            MaintainWebsocketDTO maintainWebsocketDTO = JSONUtil.parseObject(textMsg, MaintainWebsocketDTO.class);
            Integer deptId = maintainWebsocketDTO.getDeptId();
            List<SysUserDTO> users = sysUserService.getUsersByDeptId(deptId);
            for (SysUserDTO user : users) {
                WebSocketSession session = sessionManager.getSession(String.valueOf(user.getId()));
                if (session != null && session.isOpen()) {
                    session.sendMessage(new TextMessage(maintainWebsocketDTO.getContent()));
                    logger.info("maintain_websocket,推送消息:{}", maintainWebsocketDTO.getContent());
                }
            }
        } catch (Exception e) {
            logger.error("处理maintain_listener消息失败");
        }
    }


}
